<script lang="ts" setup>
import { reactive, ref } from "vue";
import api from "@/api";
import type { SseEvent } from "@/types";
import { ElMessage } from "element-plus";

const emit = defineEmits(["success"]);

interface State {
  visible: boolean;
  form: {
    id: string;
    path: string;
    file?: File;
  };
  progress: {
    transferred: string;
    max: string;
    percent: number;
    success: boolean;
  };
}

const state = reactive<State>({
  visible: false,
  form: {
    id: "",
    path: ""
  },
  progress: {
    transferred: "0",
    max: "0",
    percent: 0,
    success: false
  }
});

const fileRef = ref<HTMLInputElement | null>(null);

const handleFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  const files = target.files;
  if (files) {
    console.log(files);
    state.form.file = files[0];
  }
};

const disableSubmit = ref(false);

// Extract the core upload logic to be reusable
const _doUpload = () => {
  if (!state.form.file) {
    ElMessage.error("请选择文件");
    return;
  }

  disableSubmit.value = true;

  api.sftp.uploadSSE(state.form.id, state.form.path, state.form.file!, (event: SseEvent) => {
    state.progress = JSON.parse(event.data);
    if (state.progress.success) {
      emit("success");
      closeDialog();
    }
  });
};

const submit = () => {
  _doUpload();
};

// New method to allow external components to trigger upload with a specific file
const uploadFile = (file: File) => {
  state.form.file = file;
  _doUpload();
};

const handleOpened = () => {
  fileRef.value!.value = "";
};

const openDialog = (id: string, path: string) => {
  state.form.id = id;
  state.form.path = path;
  state.form.file = undefined;
  disableSubmit.value = false;

  state.progress = {
    transferred: "0",
    max: "0",
    percent: 0,
    success: false
  };

  state.visible = true;
};

const closeDialog = () => {
  state.visible = false;
};

defineExpose({
  openDialog,
  closeDialog,
  uploadFile // Expose the new method
});
</script>
<template>
  <el-dialog
    v-model="state.visible"
    title="上传文件"
    width="500"
    :close-on-click-modal="false"
    @opened="handleOpened"
  >
    <input type="file" hidden ref="fileRef" @change="handleFileChange" />
    <div>
      <div>
        <span>文件：{{ state.form.file?.name || "未选择" }}</span>
        <el-link type="primary" @click="fileRef?.click()">选择文件</el-link>
      </div>
      <div>{{ state.progress.transferred }}/{{ state.progress.max }}</div>
      <div>
        <el-progress :percentage="state.progress.percent" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="state.visible = false">取消</el-button>
        <el-button type="primary" @click="submit" :disabled="disableSubmit"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
